import React, { useState } from "react";
import ProForm, { ProFormText } from "@ant-design/pro-form";
import UserAPI from '@/services/ant-design-pro/user';
import { Modal, message, Image, Space } from 'antd'
import { ArrowRightOutlined } from '@ant-design/icons';
import UploadImg from '@/components/UploadImg'
import No_head from '../../../assets/image/no_head.jpg'
import m_config from '@/config/config'

const { addUser, updateUser } = UserAPI;

const CreateOrEdit = (props) => {

    const { isModalVisible, isShowModal, actionRef, setUserData, initData } = props;
    const [imgFile, setImgFile] = useState(undefined);
    const type = initData === undefined ? "添加" : "编辑";
    /**
     * 添加或编辑用户
     * @param {obj} params 参数
     * @returns 
     */
    const handleSubmit = async (params) => {
        let result;
        if (initData === undefined) { // 添加
            result = await addUser(params);
        } else { // 编辑
            if (imgFile === undefined) {
                let i = 0;
                for (let key in params) {
                    if (params[key] == initData[key]) {
                        i++;
                    }
                }
                if (i >= 3)
                    return message.error("您还未修改数据")
            }

            result = await updateUser({
                user: {
                    ...initData,
                    ...params,
                },
                file: imgFile || null
            });
        }

        if (result.status == 'ok') {
            await setUserData();
            actionRef.current.reload();
            message.success(type + "成功");
        } else {
            message.error(type + '失败：' + result.data.message);
            console.log(result.data.error);
        }
        isShowModal(false);
    }

    const setImageFile = (params) => {
        setImgFile(params);
    }

    return (<Modal
        title={`${type}用户`}
        footer={false}
        visible={isModalVisible}
        onCancel={() => isShowModal(false)}
        destroyOnClose={true}>
        {

            <ProForm
                onFinish={(values) => handleSubmit(values)}
                initialValues={initData}
            >
                {
                    initData === undefined ? "" :
                        <Space size={12}>
                            <Image
                                width={150}
                                src={m_config.local + initData.avatar_url + initData.avatar}
                                onError={(e) => {
                                    e.target.src = No_head;
                                }}
                            />
                            <ArrowRightOutlined />
                            <UploadImg setImgFile={(values) => setImageFile(values)} />
                        </Space>
                }

                <ProFormText
                    name="username"
                    label="昵称"
                    placeholder="请输入名称"
                    rules={[
                        { required: true, message: "请输入昵称" }
                    ]}
                />
                <ProFormText
                    name="email"
                    label="邮箱"
                    placeholder="请输入邮箱"
                    rules={[
                        { required: true, message: "请输入邮箱" },
                        {
                            pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                            message: '邮箱格式不正确',
                        },
                        {
                            max: 50,
                            message: '邮箱不得超过50字符',
                        },
                    ]}
                />

                <ProFormText.Password
                    name="password"
                    label="密码"
                    placeholder="请输入密码"
                    rules={[
                        { required: true, message: "请输入密码" },
                        { min: 6, message: '密码最小6位' },
                    ]}
                />
            </ProForm>
        }
    </Modal>);
}

export default CreateOrEdit;